/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年9月8日
 */
package com.massyframework.beanskin.license.signature.wizard;

import java.io.File;
import java.net.URL;
import java.util.List;

import com.massyframework.beanskin.util.version.VersionRange;

import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;


/**
 * 选择模块控制器
 * 
 * @author huangkh
 *
 */
public class SelectModuleController extends Controller {

	@FXML
	private Button btnNext;
	@FXML
	private Button btnPrevious;

	@FXML
	private Button btnAdd;
	@FXML
	private Button btnDelete;
	@FXML
	private TableView<Module> tvModule;

	@FXML
	private TableColumn<Module, String> tcName;
	@FXML
	private TableColumn<Module, String> tcAlias;
	@FXML
	private TableColumn<Module, VersionRange> tcVersionRange;
	@FXML
	private TableColumn<Module, String> tcModify;

	/**
	 * 
	 */
	public SelectModuleController() {
	}

	@Override
	protected void init() {
		this.btnNext.setDisable(!this.validateModule());
		this.btnDelete.setDisable(true);

		this.tvModule.setItems(this.getWizard().getSignatureData().getModules());
		this.tvModule.getSelectionModel().selectedItemProperty().addListener(this.selectListener);

		this.tcName.setCellValueFactory(new PropertyValueFactory<Module, String>("name"));
		this.tcAlias.setCellValueFactory(new PropertyValueFactory<Module, String>("certAlias"));
		this.tcVersionRange.setCellValueFactory(new PropertyValueFactory<Module, VersionRange>("versionRange"));

		this.tcModify.setCellFactory((col) -> {
			TableCell<Module, String> cell = new TableCell<Module, String>() {

				@Override
				public void updateItem(String item, boolean empty) {
					super.updateItem(item, empty);
					this.setText(null);
					this.setGraphic(null);

					if (!empty) {
						Button btnEdit = new Button("编辑");
						Font font = Font.font(12);
						btnEdit.setFont(font);

						this.setAlignment(Pos.CENTER);
						this.setGraphic(btnEdit);
						btnEdit.setOnMouseClicked((me) -> {
							Module module = this.getTableView().getItems().get(this.getIndex());
							editModule(module);
						});
					}
				}

			};
			return cell;
		});
	}

	protected void editModule(Module module) {
		try {
			FXMLLoader loader = new FXMLLoader();
			ClassLoader classLoader = this.getClass().getClassLoader();
			URL location = classLoader.getResource("fxml/moduleEditor.fxml");
			if (location != null) {
				loader.setLocation(location);

				Stage popupStage = new Stage();
				Scene scene = new Scene(loader.load());
				ModuleEditorController controller = loader.getController();
				controller.init(popupStage, module);

				popupStage.initOwner(this.getWizard().getStage());
				popupStage.setTitle("签发许可的模块");
				popupStage.initModality(Modality.WINDOW_MODAL);
	            popupStage.setScene(scene);
	            popupStage.showAndWait();
	            this.tvModule.refresh();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 选择监听器
	 */
	private ChangeListener<Module> selectListener = (observable, oleValue, newValue) -> {
		if (newValue != null) {
			this.btnNext.setDisable(false);
			this.btnDelete.setDisable(false);
		} else {
			this.btnNext.setDisable(true);
			this.btnDelete.setDisable(true);
		}
	};

	/**
	 * 模块信息是否有效
	 * 
	 * @return {@link boolean},返回{@code true}表示有效，否则返回{@code false}
	 */
	protected boolean validateModule() {
		return this.tvModule.getItems().size() > 0;
	}

	@Override
	public void destroy() {

	}

	@FXML
	protected void onAddClick(ActionEvent event) {
		FileChooser fileChooser = new FileChooser();
		fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("模块", "*.jar"));
		fileChooser.setTitle("选择要签发许可的模块");
		File file = fileChooser.showOpenDialog(this.getWizard().getStage());

		if (file != null) {
			ModuleParser parser = new ModuleParser();
			List<Module> modules = parser.parseJarFile(file);
			this.getWizard().getSignatureData().addAll(modules);
		}
		this.btnNext.setDisable(this.getWizard().getSignatureData().getModules().isEmpty());
	}

	@FXML
	protected void onDeleteClick(ActionEvent event) {
		Module module = this.tvModule.getSelectionModel().getSelectedItem();
		if (module != null) {
			this.getWizard().getSignatureData().getModules().remove(module);
			this.btnNext.setDisable(this.getWizard().getSignatureData().getModules().isEmpty());
		}
	}

	@FXML
	protected void onPreviousClick(ActionEvent event) {
		this.getWizard().doPrevious();
	}

	@FXML
	protected void onNextClick(ActionEvent event) {
		this.getWizard().doNext();
	}
}
